package com.chaofan.authsso.client.util;

import cn.hutool.http.HttpUtil;
import com.chaofan.authsso.client.common.ApplyTokenResult;
import com.chaofan.authsso.client.common.Constant;
import com.chaofan.authsso.client.common.SsoRestfulMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpSession;

/**
 * token操作工具类
 * Author: Chaofan
 * Date: 2020/6/4 15:46
 * email: chaofan2685@qq.com
 */
public class TokenUtil {

    public static final Logger logger = LoggerFactory.getLogger(TokenUtil.class);

    /**
     * 发送请求,校验token
     * @param ssoHost 单点登录中心端地址
     * @param token
     * @return
     */
    public static SsoRestfulMessage<ApplyTokenResult> checkToken(String ssoHost, String token){
        logger.info(LogMsgUtil.buildAuthSsoLog(Constant.BEGIN_CHECK_TOKEN_STR));
        String resultJson = HttpUtil.get(SsoUrlUtil.getCheckTokenUrl(ssoHost,token));
        return new SsoRestfulMessage(resultJson,ApplyTokenResult.class);
    }

    /**
     * 申请token
     * @param ssoHost 单点登录中心端地址
     * @return
     */
    public static SsoRestfulMessage<ApplyTokenResult> applyToken(String ssoHost, HttpSession session){
        logger.info(LogMsgUtil.buildAuthSsoLog(Constant.BEGIN_APPLY_TOKEN_STR));
        String resultJson = HttpUtil.get(SsoUrlUtil.getApplyTokenUrl(ssoHost,session.getId()));
        return new SsoRestfulMessage(resultJson,ApplyTokenResult.class);
    }

    /**
     * 退出登录
     * @param ssoHost 单点登录中心端地址
     * @return
     */
    public static SsoRestfulMessage logout(String ssoHost, String token){
        logger.info(LogMsgUtil.buildAuthSsoLog(Constant.BEGIN_INVALIDATE_TOKEN_STR));
        String resultJson = HttpUtil.get(SsoUrlUtil.getInvalidateTokenUrl(ssoHost,token));
        return new SsoRestfulMessage(resultJson);
    }

    /**
     * 检验auth-sso服务端是否正常
     * @param ssoHost
     * @return
     */
    public static boolean checkCoreService(String ssoHost){
        logger.info(LogMsgUtil.buildAuthSsoLog(Constant.AUTH_SSO_SERVICE_CHECK_STR));
        try {
            String resultJson = HttpUtil.get(SsoUrlUtil.getCheckCoreServiceUrl(ssoHost));
            SsoRestfulMessage<Boolean> ssoRestfulMessage = new SsoRestfulMessage(resultJson,Boolean.class);
            return ssoRestfulMessage.getData();
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


}
